package me.frank.security.filter;

import me.frank.security.exception.ValidateCodeException;
import me.frank.security.validate.code.ImageValidateCode;
import me.frank.security.web.ValidateCodeController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author Frank Wang
 * @Description:
 * @Date 2018/12/12 9:59
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(StringUtils.equals("/authentication/form",request.getRequestURI())&&StringUtils.equalsIgnoreCase(request.getMethod(),"post")){

            try {
                validate(request);

            }catch (ValidateCodeException e){
                failureHandler.onAuthenticationFailure(request,response,e);
                return;
            }

        }
        filterChain.doFilter(request,response);
    }

    private void validate(HttpServletRequest request) throws ServletRequestBindingException {

        HttpSession session = request.getSession();
        ImageValidateCode imageValidateCode = (ImageValidateCode)session.getAttribute(ValidateCodeController.SESSION_KEY);
        String strCode = ServletRequestUtils.getStringParameter(request, "imageValidateCode");

        if(StringUtils.isBlank(strCode)){
            throw new ValidateCodeException("验证码值不能为空");
        }

        if(imageValidateCode ==null){
            throw new ValidateCodeException("验证码不存在");
        }

        if(imageValidateCode.isExpire()){
            throw new ValidateCodeException("验证码已过期");
        }

        if(!StringUtils.equalsIgnoreCase(imageValidateCode.getCode(),strCode)){
            throw new ValidateCodeException("验证码不匹配");
        }

        session.removeAttribute(ValidateCodeController.SESSION_KEY);
    }
}
